class Node {
    constructor(element, next) {
        this.element = element;
        this.next = next;
    }
}

/**
 * add(index,element)  指定索引添加元素 
 * add(element)  直接添加元素
 * get(index)  获取指定索引元素
 * set(index,element) 修改指定索引节点内容
 * remove(index) 删除指定索引节点
 * clear() 清空链表 
 * reverse() 单向链表的反转
 */
class LinkList {
    constructor() {
        this.head = null;
        this.size = 0;
    }
    findNode (index) {
        console.log(index)
        if (index < 0 || index >= this.size) throw new Error('越界');
        let current = this.head; // 从头部开始查找
        for (let i = 0; i < index; i++) {
            current = current.next;
        }
        return current;
    }

    add (index, element) {
        if (arguments.length == 1) {
            element = index;
            index = this.size; // 让索引指向最后一项
        }
        if (index == 0) {
            const head = this.head;
            // 指向下一个
            this.head = new Node(element, head);
        } else {
            // 通过索引查找前一个节点
            const prevNode = this.findNode(index - 1);
            prevNode.next = new Node(element, prevNode.next);
        }
        this.size++;
    }
    remove (index) {
        let node;
        if (index == 0) {
            node = this.head;
            // 如果在头指针在头部,就将指针往后移动一位
            this.head == this.head.next;
        } else {
            // 删除,就找到当前需要删除的前一个节点,修改前一个节点指向下一个节点就是删除的指向的下一个节点,赋值给它就好
            const prevNode = this.findNode(index - 1);
            node = prevNode.next;
            prevNode.next = prevNode.next.next;
        }

        this.size--;
        return node;
    }
    get (index) {
        return this.findNode(index);
    }
    set (index, element) {
        const node = this.findNode(index);
        node.element = element;
    }
    clear() {
        this.size = 0;
        this.head = null;
    }

    reverse() {
        const _reverse = head => {
            if(head == null || head.next == null) {
                return head;
            }
            const newHead = _reverse(head.next);
            head.next.next = head;
            head.next = null;
            return newHead;
        }
        this.head = _reverse(this.head);
        return this.head;
    }
}

const ll = new LinkList();

ll.add("1");
ll.add("2");
ll.add(0, "3")
console.dir(ll.reverse(), {depth: 100})
